package com.thunder.rebot.rebotclient.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.limedia.explorer.centralcontrol.ControlActivity;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.constant.Constants;
import com.thunder.rebot.rebotclient.entity.LoginMessageBean;
import com.thunder.rebot.rebotclient.entity.PicRegistEntity;
import com.thunder.rebot.rebotclient.entity.QuerySQLEntity;
import com.thunder.rebot.rebotclient.entity.SocketConectState;
import com.thunder.rebot.rebotclient.entity.UserInformationEntity;
import com.thunder.rebot.rebotclient.service.ServiceClient;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.LogInUtils;
import com.ts.robot.socket.TSRobotSocketNative;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {


    private String TAG = LoginActivity.class.getSimpleName();

    @BindView(R.id.center_txt)
    public TextView centerTxt;
    @BindView(R.id.right_txt)
    public TextView rightTxt;
    @BindView(R.id.rl_back)
    public RelativeLayout rlBack;
    @BindView(R.id.et_user)
    public TextView etUser;
    @BindView(R.id.et_passwd)
    public TextView etPasswd;


    @BindView(R.id.btn_login)
    public Button btnLogin;
    @BindView(R.id.btnRegist)
    public Button btnRegist;

    private static TSRobotSocketNative mtsRobotSocketNative;
    private SharedPreferences sharedPreferences;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        ServiceClient.setOnPackageRemoveListener(LoginActivity.this);
        centerTxt.setText(R.string.login_information);
        rightTxt.setText(R.string.device_configuration);
        //default
        etUser.setText("2");
        etPasswd.setText("******");
//        mtsRobotSocketNative = TSRobotSocketNative.getTsRobotSocketNativeInstance();
        mtsRobotSocketNative.addSocketLisetnerInterface(this);
        sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ServiceClient.setOnPackageRemoveListener(LoginActivity.this);//
        mtsRobotSocketNative.addSocketLisetnerInterface(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mtsRobotSocketNative.removeSocketLisetnerInterface(this);
    }

    /*
        获取robot socket native object
         */
    public static void setRobotSocket(TSRobotSocketNative tsRobotSocketNative){
        mtsRobotSocketNative = tsRobotSocketNative;
    }
    @Override
    public void conectState(int code,final String description) {
        switch (code) {
            case 1:
                Gson gson = new Gson();
                final SocketConectState socketConectState = gson.fromJson(description, new TypeToken<SocketConectState>() {
                }.getType());

                switch (Integer.valueOf(socketConectState.getCode())) {
                    case 10://连接成功
                        ClientUtils.robotConnectFlag = true;

                        break;
                    case 9://连接断开
                        ClientUtils.robotConnectFlag = false;

                        break;
                    case 8://未连接成功
                        ClientUtils.robotConnectFlag = false;
                        break;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, socketConectState.getDescription(), Toast.LENGTH_SHORT).show();
                    }
                });

                break;
        }
    }
    @OnClick({R.id.btn_login,R.id.rl_back,R.id.right_txt,R.id.btnRegist})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnRegist:
//                if(ClientUtils.robotConnectFlag && ClientUtils.connectFlag){
                    //判断是否连接
                Log.w(TAG, "TEST: btn regist");
                    Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
//                    UserInformationEntity uife = new UserInformationEntity();
//                    uife.setName(etUser.getText().toString().trim());
//                    uife.setPasswd(etPasswd.getText().toString().trim());
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("uerinfo",uife);
//                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constants.REQUESTCODE);
//                }
//                else{
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(LoginActivity.this, "连接服务器失败",Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
                break;
            case R.id.btn_login://登录
                //校验用户名和密码，只有通过了，才可以登录和注册人脸，然后利用这个用户名字
                if(TextUtils.isEmpty(etUser.getText().toString().trim()) && TextUtils.isEmpty(etPasswd.getText().toString().trim()) && Constants.userpwdMap == null){
                    Toast.makeText(getApplicationContext(), "用户名和密码都不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(LogInUtils.passwdIsValid(etUser.getText().toString().trim(), etPasswd.getText().toString().trim(), Constants.userpwdMap)){
                    //开始登录,应该先判断是否已经注册，通过查询name字段
//                    queryRequest(etUser.getText().toString().trim());
                    userlogin("1001",etUser.getText().toString().trim(),etUser.getText().toString().trim(), etPasswd.getText().toString().trim());
                }
                break;
            case R.id.right_txt:
//                if(TextUtils.isEmpty(etUser.getText().toString().trim()) && TextUtils.isEmpty(etPasswd.getText().toString().trim()) && Constants.userpwdMap == null){
//                    Toast.makeText(getApplicationContext(), "用户名和密码都不能为空", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                if(LogInUtils.passwdIsValid(etUser.getText().toString().trim(), etPasswd.getText().toString().trim(), Constants.userpwdMap)){
//                    //注册人脸
//                    Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
//                    UserInformationEntity uife = new UserInformationEntity();
//                    uife.setName(etUser.getText().toString().trim());
//                    uife.setPasswd(etPasswd.getText().toString().trim());
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("uerinfo",uife);
//                    intent.putExtras(bundle);
//                    startActivityForResult(intent,Constants.REQUESTCODE);
//                }
                startActivity(new Intent(LoginActivity.this,WelcomeActivity.class));
                break;
            case R.id.rl_back:
                finish();
                break;
        }
    }
    /*
    登录回调
     */

    @Override
    public void loginLisetner(int code) {
        super.loginLisetner(code);
        switch (code){
            case 101:
                //开始跳转 control activity
                //存取用户名子
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("username", etUser.getText().toString().trim());
                editor.commit();
                startActivity(new Intent(LoginActivity.this, ControlActivity.class));

            break;
            case 102:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "用户名不存在", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case 103:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "用户名或者密码错误", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case 104:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "该用户已经在别的设备上面登录了，已经断开了连接", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            default:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this,"用户名或者密码错误", Toast.LENGTH_SHORT).show();
                    }
                });

            break;
        }
    }
    /*
返回查询数据库的结果
 */

    @Override
    public void getRebackType(Object value) {
        super.getRebackType(value);
        if(value instanceof PicRegistEntity){
            switch(((PicRegistEntity) value).getCode()){
                case 5:
                      if (((PicRegistEntity) value).isRigst()){//成功注册
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                                }
                            });
                            LoginActivity.this.finish();
                      }else{//注册失败，请重新拍照注册
                          runOnUiThread(new Runnable() {
                              @Override
                              public void run() {
                                  Toast.makeText(LoginActivity.this,"注册失败，请重新注册",Toast.LENGTH_SHORT).show();
                              }
                          });
                      }
                    break;
                case 10://未查询到, 还没有注册，请先注册
//                    if(((PicRegistEntity) value).isRigst()){
//                        userlogin("1001",etUser.getText().toString().trim(),etUser.getText().toString().trim(),etUser.getText().toString().trim());
//                    }else{
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(LoginActivity.this,"您还没有注册，请您先注册人脸",Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                        //直接跳转到注册人脸
//                        if(LogInUtils.passwdIsValid(etUser.getText().toString().trim(), etPasswd.getText().toString().trim(), Constants.userpwdMap)){
//                            //注册人脸
//                            Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
//                            UserInformationEntity uife = new UserInformationEntity();
//                            uife.setName(etUser.getText().toString().trim());
//                            uife.setPasswd(etPasswd.getText().toString().trim());
//                            Bundle bundle = new Bundle();
//                            bundle.putSerializable("uerinfo",uife);
//                            intent.putExtras(bundle);
//                            startActivityForResult(intent,Constants.REQUESTCODE);
//                        }
//                    }
                    break;
                    default:
                        Log.e(TAG,"getRebackType default error");
                        break;
            }
        }
    }
    /*
    对查询的数据库的结果进行判断
     */
    /*
    user login
     */
    private void userlogin(String frame, String name, String id, String pwsswd){
        LoginMessageBean loginMessageBean = new LoginMessageBean();
        loginMessageBean.setFRAME(frame);
        loginMessageBean.setID(name);
        loginMessageBean.setPW(pwsswd);
        Gson gson = new Gson();
        Log.d(TAG,"login:" + gson.toJson(loginMessageBean));
        sendData(gson.toJson(loginMessageBean));
    }

/*
查询数据库，是否存在已经注册
 */
private void queryRequest(String name){
    if(!TextUtils.isEmpty(name)){
        final QuerySQLEntity.RequestQuery requestQuery = new QuerySQLEntity.RequestQuery();
        requestQuery.type = Constants.QUERYCODE;
        requestQuery.name = name;
        new Thread("send") {
            @Override
            public void run() {
                super.run();
                ServiceClient.client.sendTCP(requestQuery);
            }
        }.start();

    }

}

    /*
    发送数据
     */
    private void sendData(String s){
        if(mtsRobotSocketNative != null){
            mtsRobotSocketNative.send_data_native(s);
        }
        else{
            Log.e(TAG, "tsRobotSocketNative NULL");
        }
    }
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        switch (requestCode) {
//            case Constants.REQUESTCODE:
//                if (resultCode == Constants.RESPONSECODE){
//                    // 注册人脸返回的结果
//                    Toast.makeText(getApplicationContext(), "收到注册人脸返回的结果", Toast.LENGTH_SHORT).show();
//                    //正式登录
//                }
//
//                break;
////            case REQUEST_ENABLE_BT:
//        }
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mtsRobotSocketNative.removeSocketLisetnerInterface(this);
    }
}
